package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public String login(User user) {
        //1.将密码进行加密处理
        String password = user.getPassword();
        //2.利用md5加密算法  进行加密
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Pass);
        //3.查询数据库数据
        User userDB = userMapper.findUserByUP(user);
        if (userDB == null){
            return null;
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid;
    }

    @Override
    public PageResult getUserList(PageResult pageResult) {
        String query = pageResult.getQuery();
//        long total = userMapper.getTotal();
        long total = userMapper.getTotal(query);
        int size = pageResult.getPageSize();
        int start = (pageResult.getPageNum() - 1) * size;
        List<User> rows = userMapper.findUserListByPage(start,size,query);
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    public void updateStatus(User user) {
        Date updated = new Date();
        user.setUpdated(updated);
        userMapper.updateStatus(user);
    }

    @Override
    public void addUser(User user) {
        Date date = new Date();
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))
            .setStatus(true)
            .setCreated(date)
            .setUpdated(date);
        userMapper.addUser(user);
    }

    @Override
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }

    @Override
    public Integer updateUser(User user) {
        user.setUpdated(new Date());
        return userMapper.updateUser(user);
    }

    @Override
    public void deleteUserById(User user) {
        userMapper.deleteUserById(user);
    }

}
